package com.petrochina.cloudconfig.util;

import com.alibaba.fastjson.JSON;
import com.petrochina.cloudconfig.domain.DeployServer;
import com.petrochina.cloudconfig.domain.Env;
import com.petrochina.cloudconfig.domain.Pkg;
import com.petrochina.cloudconfig.domain.env.EnvDeploy;
import com.petrochina.cloudconfig.domain.env.EnvSetting;
import org.springframework.beans.BeanUtils;

import java.io.File;
import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

/**
 * env util
 */
public class EnvUtil {


    private static String envFullNameRuleSplitor="-";



    public static boolean isEnvFullName(String envFullName){
        return  Pattern.matches("^([a-zA-z0-9]+\\.)+([a-zA-Z0-9]+-){1}([a-zA-Z0-9]+[.|-])+[j|w]ar-[a-zA-Z0-9]+$",envFullName);
    }



    public static void setEnv(Env env,EnvSetting envSetting,Map<String,DeployServer> deployServerMap){
        if(env != null && envSetting != null){
            //set configs
            EnvSettingUtil.setEnvConfigs(env,envSetting);
            //set deploys
            if(deployServerMap != null && deployServerMap.size()>0){
                EnvSettingUtil.setEnvDeploys(env,envSetting,deployServerMap);
            }
        }
    }








    /**
     * getDev env (contains pkgFullName、envName)
     * @param envFullName
     * @return Env
     */
    public static Env getEnv(String envFullName){
        Env env = new Env();
        int lastIndexOf = envFullName.lastIndexOf(envFullNameRuleSplitor);
        env.setEnvName(envFullName.substring(lastIndexOf+1));
        env.setPkgFullName(envFullName.substring(0,lastIndexOf));
        env.setEnvFullName(envFullName);
        return  env;
    }

    public static Env getEnv(String pkgFullName,String envName){
        Env env = new Env();
        env.setEnvName(envName);
        env.setPkgFullName(pkgFullName);
        env.setEnvFullName(pkgFullName+envFullNameRuleSplitor+envName);
        return  env;
    }












    /**
     *
     * @param pkgFullName pkg full name, e.g. abc.jar
     * @param envName env name, e.g. env
     * @return String envFullName env full name e.g. abc.jar-dev
     */
    public static String getEnvFullName(String pkgFullName,String envName){
        return pkgFullName+envFullNameRuleSplitor+envName;
    }

}

